<template>
  <div>
    <div class="main-container">
      <div style="float: right">
        <el-button
          type="primary"
          size="mini"
          @click="cofirmFinsh"
          :disabled="querenzhengliBtn"
          v-if="ddyPerssion == true && showConfirmButton == true"
          >确认整理</el-button
        >
        <el-button
          type="primary"
          size="mini"
          @click="next"
          :disabled="notNext"
          v-if="ddyPerssion == true && showConfirmButton == true"
          >下一个</el-button
        >
        <el-button type="primary" size="mini" @click="toPrint" v-show="isSendDoctor"
          >打印会诊申请单</el-button
        >
      </div>
      <el-tabs v-model="modelType" type="card" style="margin-top: 25px" @tab-click="tabClick">
        <el-tab-pane name="baseInfo" label="基本信息">
          <span slot="label">
            基本信息
          </span>
          <base-info v-if="isReady" :orders="orders"> </base-info>
        </el-tab-pane>
        <el-tab-pane name="express" label="快递信息">
          <span slot="label">
            快递信息
          </span>
          <consultation-express
            v-if="isReady"
            :orders="orders"
            :inspectionMethodList="inspectionMethodList"
          ></consultation-express>
        </el-tab-pane>
        <el-tab-pane name="consultationBiopsyView" label="病理信息">
          <span slot="label">
            病理信息
            <el-badge
              v-if="pathologicalInformationCornerLabel > 0"
              :value="pathologicalInformationCornerLabel"
              class="tab-content-badge"
            ></el-badge>
          </span>
          <ConsultationBiopsyView v-if="isReady" :orders="orders"> </ConsultationBiopsyView>
        </el-tab-pane>
        <el-tab-pane name="pathologyView" label="切片列表">
          <span slot="label">
            切片列表
            <el-badge
              v-if="sectionListCornerLabel > 0"
              :value="sectionListCornerLabel"
              class="tab-content-badge"
            ></el-badge>
          </span>
          <consultation-pathologyView v-if="isReady" :orders="orders"> </consultation-pathologyView>
        </el-tab-pane>
        <el-tab-pane v-if="consultationSuggest" name="opinion" label="会诊报告">
          <span slot="label">
            会诊报告
            <el-badge
              v-if="consultationAdviceCornerLabel > 0"
              :value="consultationAdviceCornerLabel"
              class="tab-content-badge"
            ></el-badge>
          </span>
          <consultation-opinion
            v-if="isReady"
            :orders="orders"
            @consultationRequest="consultationRequest"
          >
          </consultation-opinion>
        </el-tab-pane>
        <el-tab-pane name="inspectionReport" label="检验">
          <span slot="label">
            检验
          </span>
          <!-- <inspectionReport v-if="isReady" :orders="orders"> </inspectionReport> -->
        </el-tab-pane>
        <el-tab-pane name="checkReport" label="检查">
          <span slot="label">
            检查
          </span>
          <!-- <checkReport v-if="isReady" :orders="orders"> </checkReport> -->
        </el-tab-pane>
        <el-tab-pane name="electronicMedical" label="电子病历">
          <span slot="label">
            电子病历
          </span>
          <!-- <electronicMedical v-if="isReady" :orders="orders"> </electronicMedical> -->
        </el-tab-pane>
        <el-tab-pane name="historicalReport" label="历史报告">
          <span slot="label">
            历史报告
            <el-badge
              v-if="historicalReportCount > 0"
              :value="historicalReportCount"
              class="tab-content-badge"
            ></el-badge>
          </span>
          <historicalReport v-if="isReady" :orders="orders"> </historicalReport>
        </el-tab-pane>
        <!-- <el-tab-pane name="consultationAttachmentView" label="附件资料">
          <ConsultationAttachmentView v-if="isReady" :orders="orders"> </ConsultationAttachmentView>
        </el-tab-pane> -->
        <el-tab-pane name="extroProject" label="加做项目">
          <span slot="label">
            加做项目
            <el-badge
              :value="extroProjectCount.finishedCount + '/' + extroProjectCount.allCount"
              class="tab-content-badge"
            ></el-badge>
          </span>
          <consultationExtroProject v-if="isReady" :orders="orders"> </consultationExtroProject>
        </el-tab-pane>
        <el-tab-pane name="consultationParticipant" label="诊断流转">
          <span slot="label">
            诊断流转
          </span>
          <consultationParticipant v-if="isReady" :orders="orders"> </consultationParticipant>
        </el-tab-pane>
        <el-tab-pane label="沟通交流" name="tabDiscussion">
          <span slot="label">
            沟通交流
            <el-badge v-if="messageIdListCount > 0" :value="messageIdListCount"></el-badge>
          </span>
          <consultation-discussion
            v-if="isReady"
            :orders="orders"
            :messageList="messageBoardInfo"
            :isTheseDoctor="isTheseDoctor"
            :doctorList="doctorList"
          ></consultation-discussion>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!--startprint-->
    <div id="forPrint" class="consultation-form">
      <consultation-request-form
        v-if="printData.isReady"
        :printData="printData"
        :expressInfo="expressInfo"
      ></consultation-request-form>
    </div>
    <!--endprint-->
  </div>
</template>

<script>
import BaseInfo from '@/templates/components/ConsultationInfoView'
import ConsultationOpinion from '@/templates/components/ConsultationOpinion'
import ConsultationPathologyView from '@/templates/components/ConsultationPathologyView'
import ConsultationBiopsyView from '@/templates/components/ConsultationBiopsyView'
import ConsultationAttachmentView from '@/templates/components/ConsultationAttachmentView'
import consultationParticipant from '@/templates/components/consultationParticipant'
import historicalReport from '@/templates/components/historicalReport'

import consultationExtroProject from '@/templates/components/consultationExtroProject'
import ConsultationDiscussion from '@/templates/components/ConsultationDiscussion'
import ConsultationExpress from '@/templates/components/ConsultationExpress'
import ConsultationRequestForm from '@/templates/components/ConsultationRequestForm'
import ConsultationDefault from '@/templates/ConsultationDefault'
import _ from 'lodash'
import { $_getUnReadCountList, $_updateIsRead } from '@/network/service'
export default {
  name: 'ConsultationDetail',
  components: {
    ConsultationOpinion,
    BaseInfo,
    ConsultationPathologyView,
    ConsultationBiopsyView,
    ConsultationAttachmentView,
    ConsultationDiscussion,
    ConsultationExpress,
    ConsultationRequestForm,
    consultationParticipant,
    consultationExtroProject,
    historicalReport
  },
  data() {
    return {
      userName: this.$store.state.user.name,
      uArgs: this.$store.getters.getUArgs,
      permissionGroupList: this.$store.state.permissionList, // 权限列表数据结构
      modelType: 'opinion',
      orders: null,
      isReady: false,
      consultationSuggest: true,
      messageBoardInfo: [],
      pathologicalInformationCornerLabel: 0,
      sectionListCornerLabel: 0,
      consultationAdviceCornerLabel: 0,
      messageIdListCount: 0,
      inspectionMethodList: [],
      orderId: this.$store.getters.getUArgs.consultationId,
      ddyPerssion: false,
      notNext: false,
      querenzhengliBtn: false,
      showConfirmButton: false,
      printData: {
        createTime: '', //送检时间
        serialNumber: '', //订单号 用来生成一维码
        isReady: false,
        bedNo: '', //床号
        frozenAppointmentTime: '', //冰冻时间
        hospitalNumber: '', //住院号
        morningAndAfternoonName: '', //上下午
        pathologyId: '', //病理号
        sendingDoctor: '', //送检医生
        sendingHospitalName: '', //送检医院名称
        sendingDoctorPhone: '', //送检医生手机号
        serviceCenterName: '', //会诊医院名称
        specimenCategoryName: '', //标本类别
        typeOfConsultationName: '', //会诊类型
        typeOfConsultation: '', //会诊类型id
        visceraName: '', //取材脏器
        ward: '', //病区
        usedHospitals: '', //曾就诊医院
        diagnosisContent: '', //临床诊断
        diagnosisHistory: '', //病史摘要
        orginalPhythologyDiagnosis: '', //病理诊断
        resultPhythologyDiagnosis: '', //已做免疫组化或者分子病理结果临床诊断
        pathologyObserved: '', //病理信息-大体观察巨检
        name: '', //姓名
        sexName: '', //性别
        age: '', //年龄
        cellphone: '', //手机号码
        identicalNumber: '', //身份证号
        contactName: '', //联系人姓名
        contactWeChat: '', //联系人微信
        receivingNotes: '' // 接收备注

        // waxBlock: '',
        // whitePiece: '',
        // HE: '',
        // immunohistochemical: '',
        // radiationFilm: '',
        // paperText: '',
        // inspectionMethod: '', //送检方式
        // consignor: '', //寄件人
        // consignorPhoneNumber: '', //寄件人电话
        // sendTime: '', //快递时间
        // expressName: '', //快递公司名称
        // expressNumber: '', //快递单号
        // remark: '' //送检备注
      },
      expressInfo: [],
      isSendDoctor: false,
      opinionTabList: [],
      extroProjectCount: {
        finishedCount: 0,
        allCount: 0
      },
      historicalReportCount: 0 //历史报告角标
    }
  },
  mounted() {
    this.consultationRequest()
    this.permisson()
    this.$_getUnReadCountList()
    this.getInspectionMethodList()
    this.findMessageList()
  },
  computed: {
    doctorList() {
      const list = []
      if (
        !this.orders ||
        !this.orders.patients ||
        this.orders.patients.length == 0 ||
        !this.orders.patients[0].expertDiagnosis
      ) {
        return []
      }
      let expertDiagnosisList = this.orders.patients[0].expertDiagnosis
      expertDiagnosisList.forEach(t => {
        list.push({
          id: t.expertId,
          isInvited: t.type,
          name: t.expertName,
          expertPhone: t.expertPhone,
          isFinal: t.isFinal
        })
      })

      list.push({
        allocationUserId: this.orders.allocationUserId,
        allocationUserName: this.orders.allocationUserName,
        allocationUserPhone: this.orders.allocationUserPhone
      })
      if (this.orders.orderType === 1) {
        list.push({
          userId: this.orders.userId,
          userName: this.orders.sendingDoctor,
          userPhone: this.orders.sendingDoctorPhone,
          orderType: 1
        })
      } else if (this.orders.orderType === 2) {
        list.push({
          userId: this.orders.userId,
          userName: this.orders.patients[0].name,
          userPhone: this.orders.patients[0].cellphone,
          orderType: 2
        })
      }

      return list
    },
    userId() {
      return this.$store.state.user.id
    },
    isTheseDoctor() {
      return this.doctorList.some(t => t.id === this.userId)
    }
  },
  methods: {
    //打印会诊申请单
    async toPrint() {
      let printDataContent = document.getElementById('forPrint').innerHTML
      window.document.body.innerHTML = printDataContent
      window.print()
      location.reload()
    },

    //通过订单id获取快递内容
    getExpressInfo(id) {
      this.$axios({
        method: 'GET',
        url: `/expressInfo/get/by/expressInfo/${id}`
      }).then(res => {
        if (res && res.data.code === 200) {
          if (res.data.data.length > 0) {
            const result = res.data.data
            //1 送检 2 签收 3 回寄
            result.forEach(item => {
              if (item.sendingType === 1) {
                item.expressContent = JSON.parse(item.expressContent)
                item.expressContent.type = 3
                this.expressInfo.push(item.expressContent)
              } else if (item.sendingType === 0) {
                item.expressContent = JSON.parse(item.expressContent)
                item.expressContent.type = 1
                this.expressInfo.push(item.expressContent)
                if (!!item.signContent) {
                  let signInfo = {}
                  signInfo.expressContent = JSON.parse(item.signContent)
                  signInfo.expressContent.type = 2
                  this.expressInfo.push(signInfo.expressContent)
                }
              }
            })
          }
        }
      })
    },
    // 获取送检方式
    getInspectionMethodList() {
      this.$axios({
        method: 'get',
        url: '/dicts/list',
        params: {
          code: 'inspectionMethod'
        }
      }).then(res => {
        if (res && res.data.code === 200) {
          res.data.data.forEach(element => {
            this.inspectionMethodList.push({
              name: element.name,
              id: element.id
            })
          })
        }
      })
    },
    permisson() {
      this.permissionGroupList.forEach((item, index) => {
        if (item.name == '院外会诊') {
          this.permissionGroupList[index].permissionList.forEach((it, num) => {
            if (it.code == 'consultation-dispatch') {
              this.ddyPerssion = true
            }
          })
        }
      })
    },
    cofirmFinsh() {
      this.querenzhengliBtn = true
      this.$confirm('此操作将确定整理完成, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$axios({
            method: 'POST',
            url: `orders/updateOrdersMainBody`,
            data: {
              id: this.orderId,
              serviceStatus: 0
            }
          }).then(res => {
            if (res && res.data.code === 200) {
              this.$message.success('已确认整理!')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    next() {
      const _this = this
      this.$axios({
        method: 'GET',
        url: `orders/next/un/tide/${_this.orderId}`
      }).then(res => {
        if (res && res.data.code === 200) {
          if (res.data.data.success == true) {
            this.querenzhengliBtn = false
            _this.orderId = res.data.data.data
            _this.$store.commit('setUArgs', {
              consultationId: res.data.data.data
            })
            location.reload()
          } else if (res.data.data.success == false) {
            _this.$message.warning('已经是最后一个！')
          }
        }
      })
    },
    async tabClick() {
      if (this.modelType === 'tabDiscussion') {
        const res = await $_updateIsRead({ orderId: this.orderId })
      }
    },
    async $_getUnReadCountList() {
      const res = await $_getUnReadCountList({ orderId: this.orderId })
      if (res.code === 200) {
        this.messageIdListCount = res.data.messageIdList.length
      }
    },
    async findMessageList() {
      const _this = this
      const res = await _this.$axios({
        method: 'GET',
        url: `messageBoardController/find/message-board/${_this.uArgs.consultationId}`
      })

      if (res && res.data.code) {
        this.messageBoardInfo = res.data.data.map(item => {
          return { ...item, sendToUserName: this.reSetValue(item.messageSendToUserDetails) }
        })
      }
    },
    reSetValue(data) {
      let finalValue = ''
      data.forEach(item => {
        finalValue += item.sendToUserName
      })
      return finalValue
    },
    async consultationRequest() {
      const _this = this
      _this.isReady = false
      const res = await _this.$axios({
        method: 'GET',
        url: `/orders/${_this.uArgs.consultationId}`
      })

      if (res && res.data.code) {
        const result = res.data.data
        _this.orders = result
        _this.isSendDoctor = _this.userName === _this.orders.sendingDoctor ? true : false
        // if (_this.orders.patients[0].expertDiagnosis.length > 0) {
        //   _this.consultationSuggest = _this.orders.patients[0].expertDiagnosis.some(item => {
        //     return item.isFinal !== 1
        //   })
        // }
        _this.orders.consultationDetailList = []
        _this.orders.consultationDetailList.forEach((t, index) => {
          const detailString = _.get(t, 'detailString', '{}')
          if (detailString) {
            const detailCache = detailString.replace('\\', '')
            _this.orders.consultationDetailList[index].detailJson = JSON.parse(detailCache)
          } else {
            _this.orders.consultationDetailList[index].detailJson = {}
          }
        })
        if (
          _this.orders.serviceStatus == 5 &&
          (_this.orders.ordersStatus == 1 || _this.orders.ordersStatus == 4)
        ) {
          _this.showConfirmButton = true
        } else {
          _this.showConfirmButton = false
        }
        await this.getExpressInfo(this.orders.id)
        _this.isReady = true
        _this.angleMarker()
        _this.getExtroProjectAngleMarker()
        _this.getHistoricalReportCount()
        this.initPrintData()
      }
    },
    angleMarker() {
      this.sectionListCornerLabel = 0
      this.pathologicalInformationCornerLabel = 0
      this.orders?.patients?.[0].diagnosisHistory?.[0]?.diagnosisDataInfos.forEach(item => {
        if (item.fileType == 0) {
          this.pathologicalInformationCornerLabel += 1
        } else if (item.fileType == 3) {
          this.sectionListCornerLabel += 1
        }
      })
      if (this.isSendDoctor) {
        let _this = this
        _this.opinionTabList = _this.orders.patients[0].expertDiagnosis
        const isHaveFinalDoctor = _this.orders.patients[0].expertDiagnosis.some(
          item => item.isFinal == 1
        )
        if (isHaveFinalDoctor) {
          //有终审的医生tab列表
          _this.opinionTabList = _this.opinionTabList.filter(item => {
            return item.isFinished === 1 && item.isFinal == 1
          })
        } else {
          //无终审的医生tab列表
          _this.opinionTabList = _this.opinionTabList.filter(item => {
            return item.isFinished === 1 && item.isFinal == 0
          })
        }
        this.consultationAdviceCornerLabel = _this.opinionTabList.length
      } else {
        this.consultationAdviceCornerLabel = 0
        this.orders.patients[0].expertDiagnosis.forEach(item => {
          if (item.expertId != null) {
            this.consultationAdviceCornerLabel += 1
          }
        })
      }
    },
    //获取加做角标
    getExtroProjectAngleMarker() {
      let myList = this.orders?.patients?.[0]?.extraProjectInfos.filter(n => n.status != 0)
      this.extroProjectCount.allCount = myList.length
      this.extroProjectCount.finishedCount = myList.filter(n => {
        return n.result != null || n.resultUrl != null
      }).length
    },
    //获取历史报告角标
    getHistoricalReportCount() {
      let _this = this
      _this.dataList = _this.orders.patients[0].expertDiagnosis
      const isHaveFinalDoctor = _this.orders.patients[0].expertDiagnosis.some(
        item => item.isFinal == 1
      )
      if (isHaveFinalDoctor) {
        //有终审的医生tab列表
        _this.dataList = _this.dataList.filter(item => {
          return item.isFinished === 1 && item.isFinal == 1
        })
      } else {
        //无终审的医生tab列表
        _this.dataList = _this.dataList.filter(item => {
          return item.isFinished === 1 && item.isFinal == 0
        })
      }
      _this.historicalReportCount = _this.dataList.length
    },
    initPrintData() {
      setTimeout(() => {
        const that = this
        const patients0 = that.orders.patients[0]
        const diagnosisHistory0 = that.orders.patients[0].diagnosisHistory[0]
        Object.keys(that.printData).forEach(item => {
          if (that.orders[item]) {
            that.printData[item] = that.orders[item]
          } else if (patients0[item]) {
            that.printData[item] = patients0[item]
          } else if (diagnosisHistory0[item]) {
            that.printData[item] = diagnosisHistory0[item]
          }
        })
        this.inspectionMethodList.forEach(item => {
          if (that.printData.inspectionMethod === item.id) {
            that.printData.inspectionMethod = item.name
          }
        })
        that.printData.diagnosisHistory =
          that.orders.patients[0].diagnosisHistory[0].diagnosisHistory
        that.printData.isReady = true
      }, 500)
    }
  }
}
</script>

<style scoped>
::v-deep .el-tabs__nav-next,
::v-deep .el-tabs__nav-prev {
  font-weight: bold;
  font-size: 30px;
  color: #266eff;
}
.consultation-form {
  position: absolute;
  width: 800px;
  left: -1000px;
  top: 0;
}
/* ::v-deep .el-tabs--card > .el-tabs__header .el-tabs__item {
  box-shadow: 0px 0px 10px 8px #266EFF inset;
} */
@media only screen and (max-width: 1000px) {
  ::v-deep .el-tabs__nav-scroll {
    overflow: scroll;
  }
}
</style>
<style media="print">
@page {
  size: auto;
  margin: 0mm auto;
}
</style>
